package eppic.pkg;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.app.*;
import android.content.*;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.os.Handler;
import android.view.View.OnClickListener;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.widget.TableRow;
import android.widget.TableLayout;
import android.widget.ImageButton;

public class ViewLogsActivity extends Activity {
	
	public String project_name;
	public float rate;
	public Log[] logs;
	public Expense[] expenses;
	public float totalTime;
	public float expenseTotal;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewlogs);
        Bundle extras = getIntent().getExtras();
        
        TableLayout log_box = (TableLayout) findViewById(R.id.logs);
        ViewGroup expense_box = (ViewGroup) findViewById(R.id.expenses);
        
        //Get Type and set Name
        int id = extras.getInt("client_id");
        TextView task_name = (TextView) findViewById(R.id.task);
        TextView total_time = (TextView) findViewById(R.id.totaltime);
        TextView money_earned = (TextView) findViewById(R.id.moneyearned);
        TextView type = (TextView) findViewById(R.id.type);
        TextView expenseTotalBox = (TextView) findViewById(R.id.expensetotal);
        TextView totalBox = (TextView) findViewById(R.id.total);
        TextView rateBox = (TextView) findViewById(R.id.rate);
        TextView labelBox = (TextView) findViewById(R.id.label);
        TextView valueBox = (TextView) findViewById(R.id.value);
        
        
        if(id != 0)
        {
        	Client client = new Client(id, this);
        	project_name = client.company;
        	rate = client.rate;
        	logs = client.getLogs(this);
        	expenses = client.getExpenses(this);
        	type.setText("Client");
        	labelBox.setText("Contact: ");
        	valueBox.setText(client.client);
        }
        else
        {
        	id = extras.getInt("project_id");
        	Project project = new Project(id, this);
        	project_name = project.name;
        	rate = project.rate;
        	logs = project.getLogs(this);
        	expenses = project.getExpenses(this);
        	type.setText("Project");
        	labelBox.setText("Client: ");
        	valueBox.setText(project.getClientName(this));
        }
        
        
        if(logs.length > 0)
        {
        	for(int i = 0; i < logs.length; i++)
        	{
        		Log x = logs[i]; 
        		totalTime += x.time();
        		
        		TableRow tr = createLogRow(this, x, i);
	        		if(i%2 == 0)
	        		{
	        			tr.setBackgroundColor(Color.WHITE);
	        		}
	        		else
	        		{
	        			tr.setBackgroundColor(Color.parseColor("#33333333"));	        			
	        		}
        		log_box.addView(tr);
        	}
        }
        else
        {
        	log_box.setVisibility(8);
        }
        
        if(expenses.length > 0)
        {
        	for(int i = 0; i < expenses.length; i++)
        	{
        		Expense x = expenses[i]; 
        		
            	/*Button button = new Button(this);
    	        button.setText(x.name+" : "+x.cost);
    	        button.setOnClickListener(launch_expenseMenu);
    	        button.setTag(i);
    	        expense_box.addView(button);*/
        		TableRow tr = createExpenseRow(this, x, i);
        		if(i%2 == 0)
        		{
        			tr.setBackgroundColor(Color.WHITE);
        		}
        		else
        		{
        			tr.setBackgroundColor(Color.parseColor("#33333333"));	        			
        		}
    		expense_box.addView(tr);
        		
    	        expenseTotal += x.cost;
        	}
        }
        else
        {
        	expense_box.setVisibility(8);
        }
        
        //Format Time Worked and Money Earned and set Views
        int minutes = (int) ((totalTime / 1000) / 60);
	    int hours = minutes / 60;
	    minutes = minutes % 60;
        
        DecimalFormat twoDForm = new DecimalFormat("#.##");
	    float money = rate*(totalTime / 3600000);
        
        task_name.setText(project_name);
        total_time.setText(String.format("%d:%02d", hours, minutes)+" hrs");
        money_earned.setText("$"+twoDForm.format(money));
        expenseTotalBox.setText("$"+twoDForm.format(expenseTotal));
        totalBox.setText("$"+twoDForm.format(money + expenseTotal));
        rateBox.setText("$"+twoDForm.format(rate)+" /hr");
        
    }
    
    public TableRow createLogRow(Context context, Log log, int i)
    {
    	
    	TableRow tr = new TableRow(context);
    	
    	TextView date = new TextView(context);
    	date.setTextSize(11);
    	date.setTextColor(Color.parseColor("#333333"));
    	date.setText(log.date());
    	date.setPadding(9, 4, 9, 4);
    	tr.addView(date);
    	
    	
    	TextView start = new TextView(context);
    	start.setTextSize(11);
    	start.setTextColor(Color.parseColor("#333333"));
    	start.setText(log.startTime());
    	start.setPadding(9, 4, 9, 4);
    	tr.addView(start);
    	
    	TextView end = new TextView(context);
    	end.setTextSize(11);
    	end.setTextColor(Color.parseColor("#333333"));
    	end.setText(log.endTime());
    	end.setPadding(9, 4, 9, 4);
    	tr.addView(end);
    	
    	TextView hours = new TextView(context);
    	hours.setTextSize(11);
    	hours.setTextColor(Color.parseColor("#333333"));
    	hours.setText(log.timeWorked());
    	hours.setPadding(9, 4, 9, 4);
    	tr.addView(hours);
    	
    	//Define delete image
    	Resources res = getApplicationContext().getResources();
        Drawable deleteBtn = res.getDrawable(R.drawable.delete);
    	
    	ImageButton delete = new ImageButton(context);
    	delete.setBackgroundColor(Color.parseColor("#00000000"));
    	delete.setImageDrawable(deleteBtn);
    	delete.setPadding(6, 4, 6, 4);
    	delete.setOnClickListener(launch_logMenu);
    	delete.setTag(i);
    	tr.addView(delete);
    	
    	return tr;
    }
    
    public TableRow createExpenseRow(Context context, Expense expense, int i)
    {
    	
    	TableRow tr = new TableRow(context);
    	
    	TextView name = new TextView(context);
    	name.setTextSize(11);
    	name.setTextColor(Color.parseColor("#333333"));
    	name.setText(expense.name);
    	name.setPadding(9, 4, 9, 4);
    	tr.addView(name);
    	
    	
    	TextView cost = new TextView(context);
    	cost.setTextSize(11);
    	cost.setTextColor(Color.parseColor("#333333"));
    	cost.setText("$"+expense.cost);
    	cost.setPadding(9, 4, 9, 4);
    	tr.addView(cost);
    	
    	
    	//Define delete image
    	Resources res = getApplicationContext().getResources();
        Drawable deleteBtn = res.getDrawable(R.drawable.delete);
    	
    	ImageButton delete = new ImageButton(context);
    	delete.setBackgroundColor(Color.parseColor("#00000000"));
    	delete.setImageDrawable(deleteBtn);
    	delete.setPadding(6, 4, 6, 4);
    	delete.setOnClickListener(launch_expenseMenu);
    	delete.setTag(i);
    	tr.addView(delete);
    	
    	return tr;
    }
    
    public View.OnClickListener launch_logMenu = new View.OnClickListener()
    {
    	 public void onClick(View v) {
    		 
    		 logMenu((Integer) v.getTag());
    		 
         }
    
    };
    
    public void logMenu(int id)
    {
    	final CharSequence[] items = {"Delete"};
    	final Log log = logs[id];
    	
    	AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setItems(items, new DialogInterface.OnClickListener() {
       	    public void onClick(DialogInterface dialog, int item) {
       	    	if(items[item] == "Delete")
       	    	{
       	    		String toastMsg;
       	    		if(log.delete(ViewLogsActivity.this))
       	    		{
       	    			toastMsg = "Log Deleted";
       	    			reloadList();
       	    		}
       	    		else
       	    		{
       	    			toastMsg = "Failed to delete project. Try again.";
       	    		}
       	    		Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_SHORT).show();
       	    	}
       	    	if(items[item] == "Edit")
       	    	{
       	    		//TODO: Create Log Editing Page
       	    	}
       	    }
       	});
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle("Log "+ (id+1));
        alert.show();
    }

    public View.OnClickListener launch_expenseMenu = new View.OnClickListener()
    {
    	 public void onClick(View v) {
    		 
    		expenseMenu((Integer) v.getTag());
    		 
         }
    
    };
    
    public void expenseMenu(int id)
    {
    	final CharSequence[] items = {"Delete"};
    	final Expense expense = expenses[id];
    	
    	AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setItems(items, new DialogInterface.OnClickListener() {
       	    public void onClick(DialogInterface dialog, int item) {
       	    	if(items[item] == "Delete")
       	    	{
       	    		String toastMsg;
       	    		if(expense.delete(ViewLogsActivity.this))
       	    		{
       	    			toastMsg = "Log Deleted";
       	    			reloadList();
       	    		}
       	    		else
       	    		{
       	    			toastMsg = "Failed to delete project. Try again.";
       	    		}
       	    		Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_SHORT).show();
       	    	}
       	    	if(items[item] == "Edit")
       	    	{
       	    		//TODO: Create Log Editing Page
       	    	}
       	    }
       	});
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle("Expense "+ (id+1));
        alert.show();
    }
    
    public void goBack(View view) {
    	finish();
    }
    
    public void reloadList()
    {
    	startActivity(getIntent()); finish();
    }
    
}